package test.n00500;


import java.util.ArrayList;
import java.util.List;

import static utils.Tools.listOf;

public class Problem00541 {
    public static void main(String[] args) {
        println(new int[][]{
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        });
    }

    public static void println(int[][] matrix) {
        Solution ss = new Solution();
        System.out.println(listOf(matrix) + "," + ss.spiralOrder(matrix));
    }

    public static class Solution {

        /**
         * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
         *
         * @param matrix
         * @return
         */
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> result = new ArrayList<>();

            int ROW = matrix.length, COL = matrix[0].length;

            int left = 0, right = COL - 1, top = 0, bottom = ROW - 1;
            while (left <= right && top <= bottom) {
                for (int col = left; col <= right; col++) {
                    result.add(matrix[top][col]);
                }
                for (int row = top + 1; row <= bottom; row++) {
                    result.add(matrix[row][right]);
                }

                if (left < right && top < bottom) {
                    for (int col = right - 1; col > left ; col--) {
                        result.add(matrix[bottom][col]);
                    }

                    for (int row = bottom; row > top ; row--) {
                        result.add(matrix[row][left]);
                    }
                }
                left++;
                right--;
                top++;
                bottom--;
            }
            return result;
        }
    }
}
